using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using StupidSpaceThing;

namespace RacerGame
{
	internal class Player : Unit
	{
		private const double changeFactionLag = 1000;
		private double startChangeFaction;
		private Faction changeFaction;
		public int Score = 0;

		public Player(Vector3 position)
			: base(new PlayerEntity(position)) {
			massModifier = 40;
			turnSpeed = 1;
		}

		public void ChangeFaction(Faction newFaction, RealGameTime gameTime) {
			if( newFaction.Defeated ) return;
			changeFaction = newFaction;
			if( Faction != Faction.None ) {
				Faction.Remove(this);
				Faction.None.Add(this);
			}
			startChangeFaction = gameTime.TotalRealGameTime.TotalMilliseconds;
		}

		public override void Update(RealGameTime gameTime) {
			if( changeFaction != null && startChangeFaction + changeFactionLag < gameTime.TotalRealGameTime.TotalMilliseconds ) {
				Faction.Remove(this);
				changeFaction.Add(this);
				changeFaction = null;
			}

			Color lifeIndicator = new Color((byte)(MathHelper.Lerp(0, 255, 1 - Entity.Life / 100.0f)), (byte)(MathHelper.Lerp(0, 255, Entity.Life / 100.0f)), 0);
			//Bullets.Fire(new Bullet(lifeIndicator, this, Vector3.Down, 0, gameTime, false));
			base.Update(gameTime);
		}

		public void ApplyChainedForce(Vector2 force, bool ignoreDirection) {
			if( RacerGame.Players.Count > 1 ) {
				int position = RacerGame.Players.Count - 1;
				foreach( KeyValuePair<PlayerIndex, Player> pair in RacerGame.Players ) {
					if( pair.Value != this && pair.Value.Position.Z < Position.Z ) {
						position--;
					}
				}
				float multiplyer = position / (float)(RacerGame.Players.Count - 1);
				if( force.Y > 0 ) force.Y = force.Y * multiplyer;
			}
			ApplyForce(force, ignoreDirection);
		}
	}
}
